<?php

use think\Db;

/**
 * 计算两点地理坐标之间的距离
 * @param Decimal $longitude1 起点经度
 * @param Decimal $latitude1 起点纬度
 * @param Decimal $longitude2 终点经度
 * @param Decimal $latitude2 终点纬度
 * @param Int   $unit    单位 1:米 2:公里
 * @param Int   $decimal  精度 保留小数位数
 * @return Decimal
 */
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit = 2, $decimal = 2){
    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;
    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;
    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI /180.0;
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $distance = $distance * $EARTH_RADIUS * 1000;
    if($unit==2){
        $distance = $distance / 1000;
    }
    return round($distance, $decimal);
}

/**
 * 二维数组按指定的键值排序
 * @param $array 需要排序的二维数组
 * @param $keys 需要排序根据的索引
 * @param string $type 正序/倒叙（默认倒序）
 * @return array|string
 */
function ArraySort($array, $keys, $type = 'asc')
{
    if (!isset($array) || !is_array($array) || empty($array)) return '';
    if (!isset($keys) || trim($keys) == '') return '';
    if (!isset($type) || $type == '' || !in_array(strtolower($type), array('asc', 'desc'))) return '';

    $keysvalue = [];
    foreach ($array as $key => $val) {
        $val[$keys] = str_replace('-', '', $val[$keys]);
        $val[$keys] = str_replace(' ', '', $val[$keys]);
        $val[$keys] = str_replace(':', '', $val[$keys]);
        $keysvalue[] = $val[$keys];
    }
    asort($keysvalue); //key值排序
    reset($keysvalue); //指针重新指向数组第一个
    foreach ($keysvalue as $key => $vals)
        $keysort[] = $key;
    $keysvalue = [];
    $count = count($keysort);
    if (strtolower($type) != 'asc') {
        for ($i = $count - 1; $i >= 0; $i--)
            $keysvalue[] = $array[$keysort[$i]];
    } else {
        for ($i = 0; $i < $count; $i++)
            $keysvalue[] = $array[$keysort[$i]];
    }
    return $keysvalue;
}

function addGoodsToCart($goodsId, $goodsNum, $goods_spec_key, $userInfo, $type, $tasteNote){
    $goods = Db::name('goods')->where('goods_id', '=', $goodsId)->find();

    if(empty($goods) || $goods['is_on_sale'] != '1'){
        return array(
            'code' => 500,
            'msg' => 'error:商品已下架'
        );
    }
    //获取用户购物车的商品有多少种
    $userCartCount = Db::name('cart')->where('user_id', '=', $userInfo['userId'])
        ->count();
    if ($userCartCount >= 30) {
        return array(
            'code' => 500,
            'msg' => 'error:购物车商品太多啦!'
        );
    }
    if ($type == 'motion') {
        //运动商城
        if ($goods['cat_id'] == '13') {
            return json(array('code' => 500, 'msg' => 'error:积分商品不可加入购物车'));
        }else{
            $goodsType = 1; //运动商城的
        }
    }else{
        $goodsType = 2; //food 点餐的
    }
    $storeCount = $goods['store_count'];

    //获取商品对应的规格价钱 库存 条码
    $specGoodsPriceList = Db::name('SpecGoodsPrice')->where("goods_id", $goods['goods_id'])->cache(true, MT_CACHE_TIME)->getField("key,key_name,price,store_count");

    if(!empty($specGoodsPriceList)){
        $specPrice = $specGoodsPriceList[$goods_spec_key]['price'];
        $storeCount = $specGoodsPriceList[$goods_spec_key]['store_count'];
    }

    $userCartGoods = Db::name('cart')
        ->where('user_id', '=', $userInfo['userId'])
        ->where('goods_id', '=', $goods['goods_id'])
        ->where('spec_key', '=', $goods_spec_key)->find();

    if (!empty($userCartGoods) && $tasteNote == $userCartGoods['tasteNote']) {
        $userCartGoodsNum = $goodsNum + $userCartGoods['goods_num'];
        if($userCartGoodsNum > $storeCount){
            return array(
                'code' => 500,
                'msg' => 'error:库存不足',
            );
        }
        //没有阶梯价格，如果有规格价格，就使用规格价格，否则使用本店价。
        $price = isset($specPrice) ? $specPrice : $goods['shop_price'];
        $cartResult = Db::name('cart')
            ->where('id', '=', $userCartGoods['id'])
            ->save(array(
                'goods_num' => $userCartGoodsNum,
                'goods_price' => $price,
            ));
    }else{
        //没有阶梯价格，如果有规格价格，就使用规格价格，否则使用本店价。
        $price = isset($specPrice) ? $specPrice : $goods['shop_price'];
        $cartAddData = array(
            'user_id'  => $userInfo['userId'],   // 用户id
            'goods_id' => $goods['goods_id'],   // 商品id
            'goods_sn' => $goods['goods_sn'],   // 商品货号
            'goods_name'  => $goods['goods_name'],   // 商品名称
            'goods_price' => $price,  // 购买价
            'goods_num' => $goodsNum, // 购买数量
            'add_time'  => time(), // 加入购物车时间
            'selected'  => 1,
            'goodsType' => $goodsType,
            'tasteNote' => $tasteNote
        );
        if($goods_spec_key){
            $cartAddData['spec_key'] = $goods_spec_key;
            $cartAddData['spec_key_name'] = $specGoodsPriceList[$goods_spec_key]['key_name']; // 规格 key_name
        }
        $cartResult = Db::name('cart')->insert($cartAddData);
    }
    if($cartResult !== false){
        return array(
            'code' => 200,
            'msg' => 'success:成功加入购物车'
        );
    }else{
        return array(
            'code' => 500,
            'msg' => 'error:发生意外错误,请联系客服'
        );
    }

}


function getUserCartCout($userInfo, $selected, $goodsType){

    $where = array(
        'user_id' => $userInfo['userId'],
        'goodsType' => $goodsType,
    );
    $cartList = Db::name('cart')->alias('c')
        ->join('goods g', 'c.goods_id = g.goods_id')
        ->where('c.user_id', '=', $userInfo['userId'])
        ->where('c.goodsType', '=', $goodsType)
        ->field('c.id as cartId,c.goods_id as goodsId,c.goods_name as goodsName,c.goods_price as goodsPrice,c.goods_num as goodsNum,c.selected,c.spec_key,c.spec_key_name as specKeyName,g.original_img as goodsImages,g.goods_remark as goodsRemark,tasteNote')
        ->select();
    $total_goods_num = $total_price = 0;//初始化数据。商品总共数量/商品总额
    foreach ($cartList as &$value) {

        $value['goodsImages'] = config('site_url.site_url') . $value['goodsImages'];
        $value['goodsFee'] = $value['goodsNum'] * $value['goodsPrice']; //小计
        // 最多可购买的库存数量
        $value['storeCount'] = getGoodNum($value['goodsId'], $value['spec_key']) ? : 0;
        $total_goods_num += $value['goodsNum'];
        // 如果要求只计算购物车选中商品的价格 和数量  并且  当前商品没选择 则跳过
        if ($selected == 1 && $value['selected'] == 0){
            continue;
        }
        $total_price += $value['goodsNum'] * $value['goodsPrice'];
    }
    $num = Db::name('cart')->where($where)->where('selected', '=', 1)->count();
    return array(
        'cartList' => $cartList,
        'totalPrice' => round($total_price, 2),
        'totalNum' => $num,
    );
}

/**
 * 根据 order_goods 表扣除商品库存
 * @param type $order_id  订单id
 * @return int $count pv总值
 */
function minusStockMotion($orderId){
    $orderGoodsArr = M('order_motion_goods')->master()->where("order_id", $orderId)->select();
    foreach($orderGoodsArr as $key => $val){
        // 有选择规格的商品
        if(!empty($val['spec_key'])){   // 先到规格表里面扣除数量 再重新刷新一个 这件商品的总数量
            M('spec_goods_price')->where(['goods_id'=>$val['goods_id'],'key'=>$val['spec_key']])->setDec('store_count', $val['goods_num']);
            refresh_stock($val['goods_id']);
        }else{
            Db::name('goods')->where('goods_id', '=', $val['goods_id'])->setDec('store_count', $val['goods_num']);
        }
        M('Goods')->where("goods_id", $val['goods_id'])->setInc('sell_count',$val['goods_num']); // 增加商品销售量
    }
}

/**
 * 根据 order_goods 表扣除商品库存
 * @param type $order_id  订单id
 * @return int $count pv总值
 */
function minusStockFoods($orderId){
    $orderGoodsArr = M('order_foods_goods')->master()->where("order_id", $orderId)->select();
    foreach($orderGoodsArr as $key => $val){
        // 有选择规格的商品
        if(!empty($val['spec_key'])){   // 先到规格表里面扣除数量 再重新刷新一个 这件商品的总数量
            M('SpecGoodsPrice')->where(['goods_id'=>$val['goods_id'],'key'=>$val['spec_key']])->setDec('store_count',$val['goods_num']);
            refresh_stock($val['goods_id']);
        }else{
            M('Goods')->where("goods_id", $val['goods_id'])->setDec('store_count',$val['goods_num']); // 直接扣除商品总数量
        }
        M('Goods')->where("goods_id", $val['goods_id'])->setInc('sell_count',$val['goods_num']); // 增加商品销售量
    }
}




